#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"

SListNode* BuySListNode(SLTDateType x)
{
	SListNode* NewNode = (SListNode*)malloc(sizeof(SListNode));
	NewNode->data = x;
	NewNode->next = NULL;
	return NewNode;
}

void SListPushFront(SListNode** pplist, SLTDateType x)
{
	SListNode* NewNode = BuySListNode(x);
	if (*pplist == NULL)
	{
		*pplist = NewNode;
	}
	else
	{
		NewNode->next = *pplist;
		*pplist = NewNode;
	}
}

void SListPrint(SListNode* plist)
{
	SListNode* current = plist;
	while (current != NULL)
	{
		printf("%d->", current->data);
		current = current->next;
	}
	printf("NULL\n");
}

void SListPopFront(SListNode** pplist)
{
	assert(*pplist);
	SListNode* prev = *pplist;
	*pplist = prev->next;
	free(prev);
	prev = NULL;

}

void SListPushBack(SListNode** pplist, SLTDateType x)
{
	SListNode* NewNode = BuySListNode(x);
	if (*pplist == NULL)
	{
		*pplist = NewNode;
	}
	else
	{
		SListNode* current = *pplist;
		while (current->next != NULL)
		{
			current = current->next;
		}
		current->next = NewNode;
	}
}

void SListPopBack(SListNode** pplist)
{
	assert(*pplist);
	if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		SListNode* current = *pplist;
		SListNode* prev = *pplist;
		while (current->next != NULL)
		{
			prev = current;
			current = current->next;
		}
		free(current);
		current = NULL;
		prev->next = NULL;
	}
	
}

SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	assert(plist);
	SListNode* current = plist;
	while (current != NULL)
	{
		if (current->data != x)
		{
			return current;
		}
		else
		{
			current = current->next;
		}
	}
	return NULL;
}

// 在节点的后面插入(利用find函数)
void SListInsertAfter(SListNode* pos, SLTDateType x)
{
	assert(pos);
	SListNode* NewNode = BuySListNode(x);
	NewNode->next = pos->next;
	pos->next = NewNode;
}

//在节点的前面插入
void SListInsert(SListNode** pplist, SListNode* pos, SLTDateType x)
{
	SListNode* NewNode = BuySListNode(x);
	assert(pos);
	if (*pplist == pos)
	{
		NewNode->next = pos;
		*pplist = NewNode;
	}
	else
	{
		SListNode* posPrev = *pplist;
		while (posPrev->next != pos)
		{
			posPrev = posPrev->next;
		}
		posPrev->next = NewNode;
		NewNode->next = pos;
	}
}

//删除目标节点后面一个节点
void SListEraseAfter(SListNode* pos)
{
	if (pos->next == NULL)
		return;
	SListNode* temp = pos->next;
	pos->next = temp->next;
	free(temp);
	temp = NULL;
}

//删除目标节点
void SListErase(SListNode** pplist, SListNode* pos)
{
	if (pos == *pplist)
	{
		SListNode* temp = *pplist;
		*pplist = temp->next;
		free(temp);
		temp = NULL;
	}
	else
	{
		SListNode* current = *pplist;
		SListNode* prev = *pplist;
		while (current != pos)
		{
			prev = current;
			current = current->next;
		}
		prev->next = current->next;
		free(current);
		current = NULL;//形参，置不置空都是可以的
	}
}


void SListDestory(SListNode** pplist)
{
	assert(pplist);
	SListNode* current = *pplist;
	while (current != NULL)
	{
		*pplist = current->next;
		free(current);
		current = *pplist;
	}
}
